#coding:utf-8
'''用wtforms和数据库,还有json请求来做一个小例子'''


from flask import Flask, render_template, redirect, url_for,request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
import json



app = Flask(__name__)



class Config(object):
    SQLALCHEMY_DATABASE_URI = 'mysql://root:mysql@127.0.0.1:3306/flask_test'
    SECRET_KEY = 'FJA;LDKFJQ0=E49'
app.config.from_object(Config)


db = SQLAlchemy(app)

class Author(db.Model):
    __tablename__ = 'tbl_author'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)

    book = db.relationship('Book', backref='author')


class Book(db.Model):
    __tablename__ = 'tbl_book'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64), unique=True)
    author_id = db.Column(db.Integer, db.ForeignKey('tbl_author.id'))


#做一个表单,显示作者,书籍,提交按钮
class Form(FlaskForm):
    author = StringField(label=u'作者', validators=[DataRequired(u'作者必填')])
    book = StringField(label=u'书籍', validators=[DataRequired(u'书籍必填')])
    submit = SubmitField(label=u'保存')




@app.route('/', methods=['GET', 'POST'])
def index():
    form = Form()
    if form.validate_on_submit():
        author = form.author.data
        book = form.book.data
        print(author, book)
        au = Author(name=author)
        # au.name = author

        db.session.add(au)
        db.session.commit()

        bo = Book()
        bo.title = book
        bo.author_id = au.id
        db.session.add(bo)
        db.session.commit()


    #查询表数据,然后传给后端
    author_li = Author.query.all() #作者列表返回去

    return render_template('index.html', author_li=author_li, form=form)


@app.route('/delete', methods=['POST','GET'])
def delete():
    if request.method == 'GET':

        bid = int(request.args.get('book_id'))
        book = Book.query.get(bid)
        db.session.delete(book)
        db.session.commit()
        return redirect(url_for('index'))
    elif request.method == 'POST':

        # string类型
        # bid = request.form.get('book_id')
        data = request.data
        bid = json.loads(data).get('book_id')
        print(bid,'-------------')
        bid = int(bid)
        book = Book.query.get(bid)
        db.session.delete(book)
        db.session.commit()
        # return redirect(url_for('index'))


        resp = {'isok':1}
        return jsonify(resp)









if __name__ == '__main__':
    # db.drop_all()
    # db.create_all()
    # # app.run(debug=True)
    # wang = Author(name='王')
    # li = Author(name='李')
    # zhao = Author(name='赵')
    # db.session.add_all([wang,li,zhao])
    # db.session.commit()
    #
    #
    # xi = Book(title='西游记', author_id=wang.id)
    # shui = Book(title='水浒传', author_id=li.id)
    # san = Book(title='三国', author_id=zhao.id)
    # db.session.add_all([xi,shui,san])
    # db.session.commit()

    app.run(debug=True)














